﻿using System;
using MySql.Data.MySqlClient;

namespace UDPSocketProject
{
    public class RouterDataManager
    {

        public byte[] convertData { get; set; }
        public int byteDataLength { get; set; }

        public RouterDataManager(byte[] convertData, int byteDataLength)
        {
            this.convertData = convertData;
            this.byteDataLength = byteDataLength;
        }

        public void SaveDataFrame()
        {
            DataFrameHeaderModel dataFrameHeaderModel = DataFrameConverter.ConvertDataFrame(convertData, byteDataLength);
            InsertDataFrameHeader(dataFrameHeaderModel);
        }

        public static void InsertDataFrameHeader(DataFrameHeaderModel dataHeaderModel)
        {
            /**
                1.检查mac地址是否合法,如果mac为空，直接退出插入操作
                2.检查mac地址在Router表中是否存在，不存在则插入到Router表中，并返回主键ID
                3.在Router表中添加该mac地址路由器的状态
            **/

            if (dataHeaderModel.devmac.Length < 1)
            {
                return;     //mac地址为空，不合法，退出插入操作
            }
            SqlHelper sqlHelper = new SqlHelper();
            //int RouterID = 0;
            string proceSQL = "CALL SaveRouter('" + dataHeaderModel.devid + "','" + dataHeaderModel.devmac + "'," + dataHeaderModel.latitude + "," + dataHeaderModel.longitude + ");";
            if(sqlHelper.execStoredProcedure(proceSQL))
            {
                string idStr = sqlHelper.queryIdBySql("SELECT ID FROM Router WHERE Devmac = '" + dataHeaderModel.devmac + "';");
                if (idStr.Length > 0)    //检查要插入的数据是否存在，存在则放弃数据写入
                {
                    int RouterID = int.Parse(idStr);
                    Console.WriteLine(" √ 保存采集设备上传数据成功，采集设备Mac地址：{0}", dataHeaderModel.devmac);
                    //保存手机信息...
                    PhoneDataManager.InsertDataFrame(RouterID,dataHeaderModel.dataFrameList);
                }
            }
            else
            {
                Console.WriteLine(" X 保存采集设备信息失败，设备Mac地址：{0}", dataHeaderModel.devmac);
            }
        }
    }
}
